<?php
require_once('include/inc_database.php');
require_once('include/inc_useraccount.php');


// Open DB connection.
$dbobj = new DatabaseObject();
$dbobj->OpenConnection();

$auth = new UserAccount();

$subscribedToUsername = trim($_POST['subscribeTo']);
if ($subscribedToUsername == "") {
	$subscribedToUsername = trim($_GET['subscribeTo']);
}

//$ipAddedBy = $_SERVER['REMOTE_ADDR'];
$addedDateTime = date("Y-m-d H:i:s", time());
$username = $auth->AuthenticatedUser();


// Check for dumb, evil robots.
//if ($_POST['robot_detector'] != "abcfed") {
//	echo "<p>Error.  Please enable Javascript.";
//	exit();
//}

if (empty($username)) {
	echo "<p>Not logged in.  Must <a href='./'>log in</a> to subscribe.";
	exit();
}

// Make sure "to" user exists.
$temp = $dbobj->GetFirstCell("SELECT COUNT(*) FROM mr_useraccount WHERE username = " . ValToSQL_str($subscribedToUsername) . "");
if ($temp == 0) {
	echo "<p>Error: subscribe to user doesn't exist.";
	exit();
}

// Make user isn't already subscribed.
$temp = $dbobj->GetFirstCell("SELECT COUNT(*) FROM mr_subscription WHERE username = " . ValToSQL_str($username) . " AND subscribedToUsername = " . ValToSQL_str($subscribedToUsername) . "");
if ($temp > 0) {
	echo "<p>Error: you're already subscribed to this user.";
	exit();
}

// Insert.
$dbobj->SendQuery("INSERT INTO mr_subscription (username, subscribedToUsername, addedDateTime) VALUES (" . ValToSQL_str($username) . ", " . ValToSQL_str($subscribedToUsername) . ", '" . $addedDateTime . "')");


//Header("Location: user.php?user=" . $username);
Header("Location: user.php?user=" . $subscribedToUsername);
exit();
?>

